#!/usr/bin/env python3

from subprocess import call
import argparse
import re
import os

parser = argparse.ArgumentParser(description='Install LAPS.')
parser.add_argument('-p', '--prefix', required=True, help='Directory where to install LAPS.')
parser.add_argument('-c', '--compiler', choices=('gfortran', 'ifort'), help='Choose which Fortran compiler to use.', default='gfortran')
args = parser.parse_args()

LAPS_SRC_ROOT = os.getcwd() # LAPS does not support out source build.
LAPSINSTALLROOT = os.path.abspath(args.prefix + '/run')
LAPS_DATA_ROOT = os.path.abspath(args.prefix + '/output')

if not os.path.isdir(args.prefix):
	os.makedirs(args.prefix)

# Set some important environment variables.
os.putenv('LAPS_SRC_ROOT', LAPS_SRC_ROOT)
os.putenv('LAPSINSTALLROOT', LAPSINSTALLROOT)

# Set compilers.
if args.compiler == 'gfortran':
	os.putenv('CC', 'gcc')
	os.putenv('FC', 'gfortran')
	os.putenv('FFLAGS', '-O2 -finit-local-zero -fopenmp')
elif args.compiler == 'ifort':
	os.putenv('CC', 'icc')
	os.putenv('FC', 'ifort')
	os.putenv('FFLAGS', '-O2 -zero -qopenmp')
	os.putenv('CPPFLAGS','-I' + os.getenv('JASPER_PATH') + '/include')
	os.putenv('LDFLAGS', '-L' + os.getenv('JASPER_PATH') + '/lib')

os.system('{}/configure --prefix={} --datadir={}'.format(LAPS_SRC_ROOT, LAPSINSTALLROOT, LAPS_DATA_ROOT))
os.system('make install')

# Record source root for later use.
with open('{}/.laps'.format(LAPSINSTALLROOT), 'w') as file:
	file.write(LAPS_SRC_ROOT)
